<?php
/**
 * MySQLQueryHandler handling and execute query with MySQLDatabaseConnection
 * @package Core
 * @subpackage Database
 * @author kovacsricsi
 */
class MySQLQueryHandler implements IQueryHandler
{
	/**
	 * Returns all row from database.
	 * @access public
	 * @static
	 * @param string $query
	 * @param array $prepare
	 * @param string $name
	 * @return array
	 */
	public static function getAll($query = "", $prepare = null, $name = "default")
	{
		if ($prepare) {
			self::_prepare($query, $prepare);
		}

		$all = array();

		$resp = MySQLDatabaseConnection::executeQuery($query, $name);

		while($row = mysql_fetch_object($resp)) {
			$all[] = $row;
		}

		return $all;
	}

	/**
	 * Returns one row from database.
	 * @access public
	 * @static
	 * @param string $query
	 * @param array $prepare
	 * @param string $name
	 * @return object
	 */
	public static function getOne($query = "", $prepare = null, $name = "default")
	{
		if ($prepare) {
			self::_prepare($query, $prepare);
		}

		$one = null;

		$resp = MySQLDatabaseConnection::executeQuery($query, $name);

		if (is_resource($resp)) {
			$one = mysql_fetch_object($resp);
		}

		return $one;
	}

	/**
	 * Execute query.
	 * @access public
	 * @static
	 * @param string $query
	 * @param array $prepare
	 * @param string $name
	 * @return void
	 */
	public static function execute($query = "", $prepare = null, $name = "default")
	{
		if ($prepare) {
			self::_prepare($query, $prepare);
		}

		MySQLDatabaseConnection::executeQuery($query, $name);
	}

	/**
	 * Protect database from sqlinjection.
	 * @access protected
	 * @static
	 * @param string $query
	 * @param array $prepare
	 * @return void
	 */
	protected static function _prepare(&$query, $prepare)
	{
		$keys   = array();
		$values = array();

   		foreach($prepare as $index => $name) {
   			$keys[]   = "/(.*?):" . $index . "(?![a-zA-Z0-9_]+)/";
            $values[] = "\\1'" . MySQLDatabaseConnection::prepare($name) . "'\\2";
   		}

		$query = preg_replace($keys, $values, $query);
		$query = str_replace("\t", "", $query);

		do {
			$query = str_replace("  ", " ", $query);
		} while (ereg("  ", $query));
	}
}
?>